﻿using MQTT.Server.Controllers;
using MQTT.Server.ExtensionServer;
using MQTT.Server.ExtensionServer.MQTTClient;
using MQTT.Server.GlobalConfig;
using MQTT.Server.Handlers;
using MQTT.Server.Helper;
using MQTTnet.AspNetCore;

namespace MQTT.Server
{
    public class Startup
    {
        private readonly AppConfig _appConfig;

        public Startup(IWebHostEnvironment environment)
        {
            _appConfig = ConfigHelper.Get<AppConfig>("AppConfig", environment.EnvironmentName) ?? new AppConfig();
        }


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore();
            //应用配置
            services.AddSingleton(_appConfig);

            services.AddHostedMqttServer(
                optionsBuilder =>
                {
                    optionsBuilder.WithDefaultEndpoint();
                });

            //HttpConnectionDispatcher registered
            services.AddConnections();

            //数据库
            services.AddSqlSugarSetup(_appConfig);
            //MQTT SERVER
            services.AddMqttConnectionHandler();
            services.AddSingleton<MqttServerController>();
            //MQTT CLIENT
            services.AddMqttClientHostedService(_appConfig);
            services.AddSingleton<MqttClientServiceRegion>();


            services.AddTransient<HelloHandler>();
        }


        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="app"></param>
        /// <param name="environment"></param>
        /// <param name="mqttServer"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment, MqttServerController mqttServer)
        {

            app.UseRouting();

            app.UseEndpoints(
                endpoints =>
                {
                    endpoints.MapControllers();

                    endpoints.MapConnectionHandler<MqttConnectionHandler>(
                        _appConfig.WebSocketPath,
                        httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                            protocolList => protocolList.FirstOrDefault() ?? string.Empty);

                });

            app.UseMqttServer(
                server =>
                {
                    //连接验证
                    server.ValidatingConnectionAsync += mqttServer.OnValidateConnection;
                    server.ClientConnectedAsync += mqttServer.OnClientConnected;
                    server.ClientDisconnectedAsync += mqttServer.OnClientDisconnectedAsync;
                    server.ClientSubscribedTopicAsync += mqttServer.OnClientSubscribedTopicAsync;
                    server.ClientUnsubscribedTopicAsync += mqttServer.OnClientUnsubscribedTopicAsync;
                    server.InterceptingPublishAsync += mqttServer.OnInterceptingPublishAsync;
                    server.StoppedAsync += mqttServer.OnStoppedAsync;


                    server.ApplicationMessageNotConsumedAsync += mqttServer.OnApplicationMessageNotConsumedAsync;
                    server.ClientAcknowledgedPublishPacketAsync += mqttServer.OnClientAcknowledgedPublishPacketAsync;

                    //server.InterceptingClientEnqueueAsync += e =>
                    //{
                    //    Console.WriteLine("SenderClientId:"+  e.SenderClientId + "ReceiverClientId:"+ e.ReceiverClientId);
                    //    return Task.CompletedTask;
                    //};
                    ////操作确认
                    //server.InterceptingOutboundPacketAsync += e =>
                    //{
                    //    Console.WriteLine("ClientId:" + e.ClientId + "Endpoint:" + e.Endpoint);
                    //    return Task.CompletedTask;
                    //};
                    ////订阅
                    //server.InterceptingSubscriptionAsync += e =>
                    //{
                    //    Console.WriteLine("ClientId:" + e.ClientId + "Response:" + e.Response);
                    //    return Task.CompletedTask;
                    //};
                    ////取消订阅
                    //server.InterceptingUnsubscriptionAsync += e =>
                    //{
                    //    Console.WriteLine("ClientId:" + e.ClientId + "Response:" + e.Response);
                    //    return Task.CompletedTask;
                    //};

                });

        }

    }
}
